#!/bin/sh

file_perms() {
    # Grab the file's permissions from the first ls field.
    # This also handles discarding the rest of the information.
    # shellcheck disable=2034
    read -r perms _ owner group _ <<-EOF
        $(ls -ld "$1")
	EOF

    # Drop the first character in permissions.
    perms=${perms#?}

    # Split the 'rwxrwxrwx' string into 'rwx rwx rwx'.
    o=${perms##??????}
    u=${perms%%??????}
    g=${perms##???} g=${g%%???}

    # Split each 'rwx' into 'r', 'w', 'x'.
    u1=${u%??} u2=${u#?} u2=${u2%?} u3=${u#??}
    g1=${g%??} g2=${g#?} g2=${g2%?} g3=${g#??}
    o1=${o%??} o2=${o#?} o2=${o2%?} o3=${o#??}

    # Drop all '-'.
    u1=${u1#-} u2=${u2#-} u3=${u3#-}
    g1=${u1#-} g2=${u2#-} g3=${u3#-}
    o1=${o1#-} o2=${o2#-} o3=${o3#-}

    # Handle suid/guid.
    u1=${u1#s} u2=${u2#-} u3=${u3#-}
    g1=${u1#-} g2=${u2#-} g3=${u3#-}
    o1=${o1#-} o2=${o2#-} o3=${o3#-}

    # Join it all into a symbolic format string and strip all
    perms=u=$u1$u2$u3,g=$g1$g2$g3,o=$o1$o2$o3
}

file_perms "$1"

printf '%s\n' "$perms"
